package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.util.RedisUtil;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.service.WorkImportantDaysInfoService;
import com.pactera.madp.cp.service.sync.BusiSyncImportantDaysService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@AllArgsConstructor
public class BusiSyncImportantDaysServiceImpl implements BusiSyncImportantDaysService {

    private final RedisTemplate redisTemplate;
    private final WorkImportantDaysInfoService workImportantDaysInfoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean syncBusiness() {
        String nowDate = DateUtil.format(new Date(), Constants.DATE_FORMAT);

        // 执行同步业务
        String lockKey = RedisUtil.buildKey(Constants.SYNC_IMPORTANT_DAYS_BUSINESS_LOCK, nowDate);
        try {
            // 获取同步业务的锁
            boolean isLocked = RedisUtil.getLock(lockKey, "1", Constants.EXPIRE_TIME, TimeUnit.SECONDS);
            if (!isLocked) {
                SyncStateContext.get().setSaveLog(false);
                return false;
            }
            log.info("CRM生日业务同步获取锁成功");

            // 清除之前数据
            workImportantDaysInfoService.remove(Wrappers.emptyWrapper());
            // 同步数据
            workImportantDaysInfoService.sync();
        } finally {
            redisTemplate.delete(lockKey);
            log.info("CRM生日业务同步释放锁成功");
        }
        log.info("CRM生日业务数据同步成功");
        return true;
    }

}
